import type { Session, Folder, Tag } from '@/types/session';
import { api } from '@/api/api';
import ErrorHandler from '@/utils/errorHandler';

// 直接使用已配置好baseURL和拦截器的api实例
const apiClient = api;

type SessionsResponse = {
  sessions: Session[];
  total: number;
};

type FolderListResponse = {
  success?: boolean;
  folders?: Folder[];
};

type TagListResponse = {
  success?: boolean;
  tags?: Tag[];
};

type OllamaModelsResponse = {
  models?: Array<string | { name: string }>;
};

type ImportExcelResponse = {
  success: boolean;
  importedCount: number;
  sessions: Session[];
};

class SessionService {
  async getSessions(params: { limit?: number; offset?: number; search?: string } = {}): Promise<SessionsResponse> {
    try {
      const { data } = await apiClient.get<{ sessions: Session[]; total: number }>('/v1/sessions', { params });
      return {
        sessions: data?.sessions ?? [],
        total: data?.total ?? 0,
      };
    } catch (error: any) {
      ErrorHandler.handleError(error, '获取会话列表', 'auto');
      return {
        sessions: [],
        total: 0,
      };
    }
  }

  async createSession(data: { id?: string; title?: string; tags?: string[] } = {}) {
    try {
      const response = await apiClient.post<Session>('/v1/sessions', data);
      return response.data;
    } catch (error: any) {
      const status = error?.response?.status
      if (status === 409) {
        // 会话已存在，直接返回服务端已有数据
        const existing = await apiClient.get<Session>(`/v1/sessions/${data.id}`)
        return existing.data
      }
      ErrorHandler.handleError(error, '创建会话', 'auto');
      throw error;
    }
  }

  async updateSession(sessionId: string, data: { title?: string }) {
    try {
      const response = await apiClient.patch<Session>(`/v1/sessions/${sessionId}`, data);
      return response.data;
    } catch (error: any) {
      ErrorHandler.handleError(error, '更新会话', 'auto');
      throw error;
    }
  }

  async deleteSession(sessionId: string): Promise<void> {
    try {
      await apiClient.delete(`/v1/sessions/${sessionId}`);
    } catch (error: any) {
      ErrorHandler.handleError(error, '删除会话', 'auto');
      throw error;
    }
  }

  async deleteSessions(sessionIds: string[]): Promise<void> {
    try {
      await apiClient.delete('/v1/sessions/batch', {
        data: { session_ids: sessionIds },
      });
    } catch (error: any) {
      ErrorHandler.handleError(error, '批量删除会话', 'auto');
      throw error;
    }
  }

  async exportSessions(sessionIds: string[]) {
    try {
      const response = await apiClient.post('/v1/sessions/export', {
        session_ids: sessionIds,
      });
      if (response.data.error) {
        throw new Error(response.data.error);
      }
      return response.data;
    } catch (error: any) {
      ErrorHandler.handleError(error, '导出会话', 'auto');
      throw error;
    }
  }

  async getFolders(): Promise<Folder[]> {
    try {
      const { data } = await apiClient.get<FolderListResponse>('/v1/sessions/folders/list');
      if (data?.error) {
        throw new Error(data.error);
      }
      return data?.folders ?? [];
    } catch (error: any) {
      ErrorHandler.handleError(error, '获取文件夹列表', 'auto');
      // 返回空列表，确保UI不会崩溃
      return [];
    }
  }

  async getTags(): Promise<Tag[]> {
    try {
      const { data } = await apiClient.get<TagListResponse>('/v1/sessions/tags/list');
      if (data?.error) {
        throw new Error(data.error);
      }
      return data?.tags ?? [];
    } catch (error: any) {
      ErrorHandler.handleError(error, '获取标签列表', 'auto');
      // 返回空列表，确保UI不会崩溃
      return [];
    }
  }

  async getOllamaModels(): Promise<string[]> {
    try {
      const { data } = await apiClient.get<OllamaModelsResponse>('/v1/llm/ollama/models');
      if (data?.error) {
        throw new Error(data.error);
      }
      const rawModels = Array.isArray(data?.models) ? data.models : [];
      return rawModels
        .map((model) => (typeof model === 'string' ? model : model?.name))
        .filter((name): name is string => Boolean(name));
    } catch (error: any) {
      ErrorHandler.handleError(error, '获取Ollama模型', 'auto');
      return [];
    }
  }

  async refreshOllamaModels(): Promise<{ success: boolean; message?: string }> {
    try {
      const { data } = await apiClient.post<{ success: boolean; message?: string }>(
        '/v1/llm/ollama/refresh-models'
      );
      if (data?.error) {
        throw new Error(data.error);
      }
      return data ?? { success: true };
    } catch (error: any) {
      ErrorHandler.handleError(error, '刷新Ollama模型', 'auto');
      return { success: false, message: '刷新模型失败' };
    }
  }

  async importExcel(file: File): Promise<ImportExcelResponse> {
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await apiClient.post<ImportExcelResponse>('/v1/datasets/import/excel', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      if (response.data.error) {
        throw new Error(response.data.error);
      }
      return response.data;
    } catch (error: any) {
      ErrorHandler.handleError(error, '导入Excel文件', 'auto');
      throw error;
    }
  }
}

export default new SessionService();
